const Joi = require('joi')
const axios = require('axios')
const JWT = require('jsonwebtoken')
const config = require('../config');
const models = require('../models')
const decryptData = require('../utils/decrypted-data')
const GROUP_NAME = 'users'

module.exports = [
    {
        method: 'POST',
        path: `/${GROUP_NAME}/createJWT`,
        handler: async (request, reply) => {
            const generateJWT = (jwtInfo) => {
                const payload = {
                    userId: jwtInfo.userId,
                    exp: Math.floor(new Date().getTime() / 1000) + 7 * 24 * 3600
                }
                return JWT.sign(payload, process.env.JWT_SECRET)
            }
            reply(generateJWT({
                userId: 1
            }))
        },
        config: {
            tags: ['api', GROUP_NAME],
            description: '用户测试的用户JWT签发',
            auth: false,// 约定此接口不参与 JWT 的用户验证，会结合下面的 hapi-auth-jwt 来使用
        }
    },
    {
        method: 'POST',
        path: `/${GROUP_NAME}/wxLogin`,
        handler: async (req, reply) => {

            const appid = config.wxAppid;
            const secret = config.wxSecret;
            const { code, encryptedData, iv } = req.payload;

            const response = await axios({
                url: 'https://api.weixin.qq.com/sns/jscode2session',
                method: 'GET',
                params: {
                    appid,
                    secret,
                    js_code: code,
                    grant_type: 'authorization_code'
                }
            })
            // response 中返回 openid 与 session_key
            const { openid, session_key } = response.data

            let user;
            try {
                // 基于 openid 查找或创建一个用户
                user = await models.users.findOrCreate({
                    where: { open_id: openid }
                })
            } catch (err) {
                console.info('查找或创建用户====>', err)
            }

            let userInfo;
            try {
                // decrypt 解密用户信息
                userInfo = decryptData(encryptedData, iv, session_key, appid)
            } catch (error) {
                console.info('解密====>', err)
            }

            try {
                // 更新 user 表中的用户的资料信息
                await models.users.update({
                    nick_name: userInfo.nickName,
                    gender: userInfo.gender,
                    avatar_url: userInfo.avatarUrl,
                    open_id: openid,
                    session_key: session_key
                }, {
                    where: { open_id: openid }
                })
            } catch (err) {
                console.info('更新====>', err)
            }

            let generateJWT;
            try {
                // 签发 jwt
                generateJWT = (jwtInfo) => {
                    const payload = {
                        userId: jwtInfo.userId,
                        exp: Math.floor(new Date().getTime() / 1000) + 7 * 24 * 60 * 60
                    }
                    return JWT.sign(payload, config.jwtSecret)
                }
            } catch (err) {
                console.info('签发 jwt ====>', err)
            }
            let data = {
                success: true,
                code: 200,
                msg: 'ok',
                data: {
                    token: generateJWT({
                        userId: user[0].id
                    }),
                    nick_name: user[0].nick_name,
                    avatar_url: user[0].avatar_url,
                    open_id: user[0].open_id,
                }
            }
            reply(data)
        },
        config: {
            auth: false,
            tags: ['api', GROUP_NAME],
            validate: {
                payload: {
                    code: Joi.string().required().description('微信用户登录的临时code'),
                    encryptedData: Joi.string().required().description('微信用户信息encryptedData'),
                    iv: Joi.string().required().description('微信用户信息iv')
                }
            }
        }
    },
]